﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace PropertyManagment.config.jwt {
    public class JwtToken {

        public static string getToken(JwtConfig jwtConfig, string username, List<string> roles) {
            //var jwtConfig = configuration.GetSection("JwtConfig").Get<JwtConfig>();

            //定义发行人issuer
            //string iss = "JWTBearer.Auth";
            //string iss = configuration["Jwt:Issuer"];
            string iss = jwtConfig.issuer;
            //定义受众人audience
            //string aud = "api.auth";
            string aud = jwtConfig.audience;

            //定义许多种的声明Claim,信息存储部分,Claims的实体一般包含用户和一些元数据
            IEnumerable<Claim> claims = new Claim[]{
                new Claim(ClaimTypes.Name, username)
            };

            //添加用户权限
            foreach (var role in roles) {
                claims = claims.Append(new Claim(ClaimTypes.Role, role));
            }

            //notBefore  生效时间
            // long nbf =new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();
            var nbf = DateTime.UtcNow;
            //expires   //过期时间
            // long Exp = new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds();
            var exp = DateTime.UtcNow.AddSeconds(Convert.ToDouble(jwtConfig.expires));
            //signingCredentials  签名凭证
            //string sign = "q2xiARx$4x3TKqBJ"; //SecurityKey 的长度必须 大于等于 16个字符
            string sign = jwtConfig.signingKey;
            var secret = Encoding.UTF8.GetBytes(sign);
            var key = new SymmetricSecurityKey(secret);
            var signcreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(issuer: iss, audience: aud, claims: claims, notBefore: nbf, expires: exp, signingCredentials: signcreds);
            var JwtHander = new JwtSecurityTokenHandler();
            var token = JwtHander.WriteToken(jwt);
            return token;
        }
    }
}
